package org.springblade.modules.door.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.alimqtt.annotation.AliListener;
import org.springblade.modules.alimqtt.annotation.AliMsgService;
import org.springblade.modules.alimqtt.message.MsgPayload;
import org.springblade.modules.door.emus.DoorConstant;
import org.springblade.modules.door.entity.DoorDevice;
import org.springblade.modules.door.listener.model.HeartBeatMsg;
import org.springblade.modules.door.mapper.DoorDeviceMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@AliMsgService
@Slf4j
@ConditionalOnProperty(name ="aliyun.mqtt.enable", havingValue = "true",matchIfMissing = false)
public class DoorMsgListener {
	@Resource
	private DoorDeviceMapper doorDeviceMapper;
	@Lazy
	@Resource
	private DoorMsgListener self;

    @AliListener(topic = "door/client/+/heart")
    public void doorHeartBeat(MsgPayload msgPayload){
		log.info("door心跳消息{}", JSON.toJSONString(msgPayload));
		self.doorHeartBeat(msgPayload);
    }

	@Async("coffeeTaskExecutor")
    public void updateDoorDevice(MsgPayload msgPayload){
		try {
			HeartBeatMsg heartBeatMsg = JSON.parseObject(msgPayload.getMessage(), HeartBeatMsg.class);
			String deviceNo = msgPayload.getDeviceNo();
			LambdaUpdateWrapper<DoorDevice> updateWrapper = Wrappers.lambdaUpdate();
			updateWrapper.eq(DoorDevice::getDeviceCode,deviceNo);
			updateWrapper.eq(DoorDevice::getDeviceState, DoorConstant.DeviceState.ON);
			updateWrapper.set(DoorDevice::getHeartTime,new Date(msgPayload.getBornTime()));
			doorDeviceMapper.update(null,updateWrapper);
		} catch (Exception e) {
			log.error("更新开门柜设备状态异常");
		}
	}
}
